package tlias.ExceptionHandler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tlias.exception.ClazzWithStudentException;
import tlias.pojo.Result;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result exceptionHandler(Exception e) {
        log.error("服务器发生异常: {}", e.getMessage());
        return Result.error("服务器发生异常");
    }
    @ExceptionHandler
    public Result exceptionHandler(DuplicateKeyException e) {
        String msg = e.getMessage();
        int index = msg.indexOf("Duplicate entry");
        String errMsg = msg.substring(index);
        String[] arr = errMsg.split(" ");
        return Result.error(arr[2]+" already existed");
    }
    @ExceptionHandler
    public Result clazzWithStudentExceptionHandler(ClazzWithStudentException e) {
        log.error("班级有学生异常:{}", e.getMessage());
        return Result.error(e.getMessage());
    }
}
